package pres.man.interview.simple;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 死锁
 *
 * @author MAN
 * @date 2020-12-08 22:05
 * @project
 * @since
 */
public class DeadLock {

    private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(5, 8, 20, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) {
        DeadLock lock = new DeadLock();
        for (int i = 0; i < 5; i++) {
            POOL.execute(() -> {
                for (; ; ) {
                    lock.thread1();
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            POOL.execute(() -> {
                for (; ; ) {
                    lock.thread2();
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private static Object resources1 = new Object();
    private static Object resources2 = new Object();

    public void thread1() {
        synchronized (resources1) {
            System.out.println("wait resources2");
            synchronized (resources2) {
                System.out.println("i get all");
            }
        }
    }

    public void thread2() {
        synchronized (resources2) {
            System.out.println("wait resources1");
            synchronized (resources1) {
                System.out.println("i get all");
            }
        }
    }
}
